import isNil from "lodash/isNil";
import { MysqlDataSource } from "ROOT/db/orm";
import TradeAccountEntity from "./TradeAccount.entity";
import { omit } from "lodash";
import SymbolOrderConfigService from "../symbol-order-config/SymbolOrderConfig.service";
import { cryptoHelper } from 'ROOT/utils/crypto'
export const KEYS = {
  access_key: 'secret_key' as const,
  secret_key: 'access_key' as const
}

class TradeAccountService {
  private repository = MysqlDataSource.getRepository(TradeAccountEntity);

  async find(query: Partial<Omit<TradeAccountEntity, 'id'>>) {
    const res = await this.repository.find({
      where: query,
    });
    return res.map(item => {
      return {
        ...item,
        access_key: item.access_key,
        secret_key: item.secret_key,
      }
    });
  }

  async findOne(query: Partial<TradeAccountEntity>, safe: boolean) {
    const data = await this.repository.findOne({
      where: query,
    });
    if (safe) {
        return data
    }
    return omit(data, ['access_key', 'secret_key']) as TradeAccountEntity;
  }

  async updateOne(id: number, newData: Partial<TradeAccountEntity>) {

    return await this.repository.update(id, newData);
  }

  async deleteOne(id: number) {
    const target = await this.findOne({ id }, false);
    if (!target) {
      return Promise.reject('删除出错' + id);
    }
    // const symbolOrderConfig = await SymbolOrderConfigService.findOne({trade_ccount_id: target.id})
    // if (symbolOrderConfig) {
    //   throw Error(`还存在引用订单 ${symbolOrderConfig.symbol}`)
    // }
    const deleted = await this.repository.delete(id);
    if (isNil(deleted)) {
      return Promise.reject('删除出错');
    }
    return;
  }

  async create(data: Partial<TradeAccountEntity>) {
    const tradeAccountEntity = new TradeAccountEntity();
    Object.assign(tradeAccountEntity, data);
    return await this.repository.save(tradeAccountEntity);
  }
}

export default new TradeAccountService();